package com.wx.web.controller.trade;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eachonline.core.JsonResult;
import com.eachonline.util.StringUtil;
import com.wx.business.WXConfig;
import com.wx.business.course.IxbCourseDetailService;
import com.wx.business.course.OrderRecordService;
import com.wx.business.trade.IxbTradeRecordService;
import com.wx.business.trade.WXPushMessageService;
import com.wx.business.weixin.WXUtil;
import com.wx.business.weixin.common.RandomStringGenerator;
import com.wx.business.weixin.common.Signature;
import com.wx.business.weixin.common.XMLParser;
import com.wx.business.weixin.protocol.WxinPaySignatureDataH5;
import com.wx.model.IxbCourseDetail;
import com.wx.model.IxbUser;


/**
 * @author 
 * 余额只付
 */
@Controller
@RequestMapping("/pay")
public class PayController   {
	
	@Autowired
	public  WXPushMessageService  wXPushMessageService;
	
	@Autowired
	public  IxbTradeRecordService  ixbTradeRecordService;
	
	@Autowired
	public  IxbCourseDetailService  ixbCourseDetailService;
	
	
	@Autowired
	public  OrderRecordService  orderRecordService;
	
	
	 private static Logger LOGGER = LoggerFactory.getLogger(PayController.class);
	
	
	@RequestMapping(value="/notifyPayForwx")
	public void notifyPayForwx(HttpServletRequest request,HttpServletResponse response) throws Exception{
		try {
			LOGGER.info(" begin:notifyPayForwx:------------------------------------------");
		   InputStream inStream=request.getInputStream();
		   ByteArrayOutputStream outStream=new ByteArrayOutputStream();
		   byte[] buffer=new byte[1024];
		   int len = 0;
		   while((len =inStream.read(buffer)) !=-1){
			   outStream.write(buffer, 0, len);
		   }
		   LOGGER.info("pay Success=============================");
		   outStream.close();
		   inStream.close();

		   //获取微信调用我们的notify_url的返回信息
		   String result=new String(outStream.toByteArray(),"utf-8");
		   LOGGER.info("result---------------------"+result);
		   LOGGER.info("signature ------------"+Signature.checkIsH5SignValidFromResponseString(result));
		   Map<String,Object> map=XMLParser.getMapFromXML(result);
			LOGGER.info("wx-支付:------------------------------------------"+map);
			String mchid=map.get("mch_id").toString();   //回调后的mdc_id 商户号
			String appid=map.get("appid").toString();   //回调后的appid
		   if(map.get("return_code").toString().equalsIgnoreCase("SUCCESS") && Signature.checkIsH5SignValidFromResponseString(result) && (WXConfig.MerID).equals(mchid) && (WXConfig.SAppID).equals(appid))
		   {
			   
			/*   Map<String,String> newMap =new HashMap<String,String>();
			   for (Map.Entry<String, Object> entry : map.entrySet()) {
			          if(entry.getValue() instanceof String){
			               newMap.put(entry.getKey(), (String) entry.getValue());
			             }
			    }*/
			   
			     ixbTradeRecordService.afterTradeStatus(map.get("out_trade_no")+"",map.get("transaction_id")+"");
				
				 response.getWriter().write(setXML("SUCCESS", "OK"));
					
		      }
		  
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				  response.getWriter().write(setXML("FAIL", "ERROR"));;
			}
		 response.getWriter().write(setXML("FAIL", "ERROR"));
		   
	 }
	


	/**
	 * 获取请求参数中所有的信息
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, String> getAllRequestParam(final HttpServletRequest request) {
		Map<String, String> res = new HashMap<String, String>();
		Enumeration<?> temp = request.getParameterNames();
		if (null != temp) {
			while (temp.hasMoreElements()) {
				String en = (String) temp.nextElement();
				String value = request.getParameter(en);
				res.put(en, value);
				//在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
				//System.out.println("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
				if (null == res.get(en) || "".equals(res.get(en))) {
					res.remove(en);
				}
			}
		}
		return res;
	}
	
	/**
	 * 微信回调接口
	 * @param return_code
	 * @param return_msg
	 * @return
	 */
	public static String setXML(String return_code,String return_msg){
		return "<xml><return_code><![CDATA["+return_code+
				"]]></return_code><return_msg><![CDATA["+return_msg+
				"]]></return_msg></xml>";
	}
		
	/**
	 *  微信下单接口
	 * @param body
	 * @param detail
	 * @param attach
	 * @param out_trade_no
	 * @param totalFee
	 * @param trade_type
	 * @param orderNo
	 * @param openId
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/wxOrder", method = { RequestMethod.POST })
	@ResponseBody
	public JsonResult wxOrder( String body, String detail, String attach, String out_trade_no,double totalFee,
			String trade_type,String orderNo,String openId,HttpServletResponse response,HttpServletRequest request) {
		  response.setHeader("Access-Control-Allow-Origin", "*");
		  response.setHeader("Access-Control-Allow-Methods", "POST");
		   IxbUser user=(IxbUser) request.getSession().getAttribute("currentAccount");
		   String sellerId = request.getParameter("sellerId");//卖家ID
           String goodsId = request.getParameter("goodsId");  //商品Id
           String goodsPic = request.getParameter("goodsPic");//主图key
           String arcName = request.getParameter("arcName");//卖家名称
           
		   if(StringUtil.isEmpty(sellerId))
		   {
			   return new JsonResult(false, "统一下单失败:卖家ID为空");
		   }
		 
		   if(StringUtil.isEmpty(goodsId))
		   {
			   return new JsonResult(false, "统一下单失败:商品ID为空");
		   }
        
		   IxbCourseDetail course= ixbCourseDetailService.selectByPrimaryKey(goodsId);
		   if(course==null)
		   {
			   return new JsonResult(false, "统一下单失败:商品不存在为空");
		   }
	       
	    int fee= (new Double(totalFee*100)).intValue(); 
		String	spbill_create_ip=request.getRemoteAddr();
		try {
			String prepayid ="";
			//out_trade_no=out_trade_no+RandomStringGenerator.getRandomStringByLength(3);
			prepayid = WXUtil.orderH5Pay( body, detail, attach, out_trade_no,fee,
						spbill_create_ip,trade_type,openId);
		
			if (null != prepayid && !"".equals(prepayid)) {
				 String noncestr= RandomStringGenerator.getRandomStringByLength(32);
				 String timestamp=String.valueOf(System.currentTimeMillis() / 1000);
				WxinPaySignatureDataH5 h5AppDate=new WxinPaySignatureDataH5(prepayid, noncestr, timestamp, WXConfig.SAppID);
			  
				//orderRecordService.createOrder(sellerId, user.getSid(), goodsId, goodsPic,orderNo, arcName, course.getCourseTitle(), course.getCourseIntro(), course.getCoursePrice(), totalFee);
				
				System.out.println("=========================="+h5AppDate);
				return new JsonResult(true, "统一下单成功", h5AppDate);
			}
			return new JsonResult(false, "统一下单失败");

		} catch (Exception e) {
			e.printStackTrace();
			return new JsonResult(false, "统一下单错误");
		}
	}
	
	
		
}
